package com.guohe3.just.common.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 浦希成
 * 2018-11-30
 * Okhttp工具类
 */
@Slf4j
public class OKHttpUtil {
    private OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            //管理cookie
            .cookieJar(new CookieJar() {
                private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    cookieStore.put(url.host(), cookies);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = cookieStore.get(url.host());
                    return cookies != null ? cookies : new ArrayList<>();
                }
            })
            .build();


    /**
     * get请求 同步 得到文件流
     *
     * @param url url
     * @return
     */
    public InputStream getFileStream(String url) {

        Request.Builder requestBuilder = new Request.Builder()
                .get()
                .url(url);

        try {
            Response response = client.newCall(requestBuilder.build()).execute();
            if (response.isSuccessful() && response.body() != null) {
                return response.body().byteStream();
            }
        } catch (Exception e) {
            log.error("Get error：{}", e);

        }
        return null;
    }

}
